/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package gestion;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
import javax.swing.JFormattedTextField;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import static javax.swing.SwingConstants.CENTER;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.NumberFormatter;
import org.jvnet.substance.SubstanceLookAndFeel;
import org.jvnet.substance.api.ColorSchemeAssociationKind;
import org.jvnet.substance.api.ComponentState;
import otros.Util;
import tablasSql.Articulos;
import tablasSql.Compras;
import tablasSql.Familias;

/**
 *
 * @author FERRETERIA
 */
public class FListArticulos extends javax.swing.JInternalFrame {

    private String quienMeLLamo = "";
    private JInternalFrame padre;
    private boolean init;
            
    public FListArticulos() {
        init();
    }
    
    public FListArticulos(JInternalFrame padre, String valor, String aBuscar) {
        this.quienMeLLamo = valor;
        this.padre = padre;
        init();
        if(aBuscar != null)
            Actualizar_Tabla(aBuscar);
    }
    
    private void init() {
        init = true;
        initComponents();
        AnchoColumnas();
        tabla.setColumnSelectionAllowed(false);
        tabla.setAutoCreateRowSorter(true);
        bBuscar.setFocusable(false);
        txtBusq.requestFocus(true);
        
        Object [][] familias = Familias.getFamilias("");
        for (int i = 0; i < familias.length; i++)
            cbFamilia.addItem(familias[i][2]);
        cbFamilia.addItem("");
        cbFamilia.setSelectedIndex(cbFamilia.getItemCount()-1);
        init = false;
    }

    private void AnchoColumnas() {
        DefaultTableColumnModel colModel = (DefaultTableColumnModel)tabla.getColumnModel();
        TableColumn col = colModel.getColumn(1);        
        col.setPreferredWidth(500);
        col = colModel.getColumn(2);
        col.setPreferredWidth(100);
        col = colModel.getColumn(3);
        col.setPreferredWidth(100);
       
    }
  
    private void enviarArticulo(String id, boolean enter) {
        switch(quienMeLLamo) {
            case Util.FTPV:
                ((FTPV)padre).txtBuscar.setText(id);
                ((FTPV)padre).añadirArticulo();
                this.dispose();
                break;
            case Util.FCOMPRAS:
                ((FCompras)padre).setIdArticuloFromFList(id, enter);
                quienMeLLamo = "";
                this.dispose();
                break;
        }     
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jScrollPane1 = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtBusq = new javax.swing.JTextField();
        bBuscar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        cbFamilia = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Lista de Articulos");
        setToolTipText("");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/img/icono2.png"))); // NOI18N
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosed(evt);
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });
        getContentPane().setLayout(new java.awt.GridBagLayout());

        jScrollPane1.setMinimumSize(new java.awt.Dimension(250, 250));
        jScrollPane1.setPreferredSize(new java.awt.Dimension(350, 250));

        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
            },
            new String [] {
                "Codigo", "Detalle", "Precio", "Costo", "Stock"
            }

        ));
        tabla.setToolTipText("<html>click raton: enviar codigo a ventana que lo llamo <br> click dcho: abrir articulo</html>");
        tabla.setColumnSelectionAllowed(true);
        tabla.getTableHeader().setReorderingAllowed(false);
        tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                tablaMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                tablaMouseExited(evt);
            }
        });
        tabla.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                tablaMouseMoved(evt);
            }
        });
        tabla.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tablaKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tablaKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(tabla);
        tabla.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 10);
        getContentPane().add(jScrollPane1, gridBagConstraints);

        jPanel1.setMinimumSize(new java.awt.Dimension(530, 65));
        jPanel1.setName(""); // NOI18N
        jPanel1.setPreferredSize(new java.awt.Dimension(530, 65));
        jPanel1.setLayout(new java.awt.GridBagLayout());

        jLabel1.setText("Criterio de busqueda:   ");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        jPanel1.add(jLabel1, gridBagConstraints);

        txtBusq.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtBusq.setToolTipText("");
        txtBusq.setMinimumSize(new java.awt.Dimension(250, 25));
        txtBusq.setPreferredSize(new java.awt.Dimension(250, 25));
        txtBusq.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtBusqMouseClicked(evt);
            }
        });
        txtBusq.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtBusqKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBusqKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        jPanel1.add(txtBusq, gridBagConstraints);

        bBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/buscar.png"))); // NOI18N
        bBuscar.setToolTipText("Buscar");
        bBuscar.setDefaultCapable(false);
        bBuscar.setMinimumSize(new java.awt.Dimension(60, 60));
        bBuscar.setPreferredSize(new java.awt.Dimension(60, 60));
        bBuscar.setRequestFocusEnabled(false);
        bBuscar.setRolloverEnabled(false);
        bBuscar.setVerifyInputWhenFocusTarget(false);
        bBuscar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bBuscarMouseClicked(evt);
            }
        });
        bBuscar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                bBuscarKeyPressed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 3;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
        jPanel1.add(bBuscar, gridBagConstraints);

        jLabel2.setText("Familia");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 0);
        jPanel1.add(jLabel2, gridBagConstraints);

        cbFamilia.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbFamiliaItemStateChanged(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 0);
        jPanel1.add(cbFamilia, gridBagConstraints);

        jLabel3.setText("Codigo o Detalle o Codigo barras");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
        jPanel1.add(jLabel3, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 10);
        getContentPane().add(jPanel1, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bBuscarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bBuscarMouseClicked
        Actualizar_Tabla();
    }//GEN-LAST:event_bBuscarMouseClicked

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        // TODO add your handling code here:
 
    }//GEN-LAST:event_formKeyPressed

    
    private void txtBusqKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBusqKeyPressed
        if (evt.getKeyCode() == 10) { 
           Actualizar_Tabla();
           txtBusq.requestFocus();
        }
    }//GEN-LAST:event_txtBusqKeyPressed

    private void bBuscarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_bBuscarKeyPressed
        if (evt.getKeyCode() == 10) {
            Actualizar_Tabla();
            txtBusq.requestFocus();
        }
    }//GEN-LAST:event_bBuscarKeyPressed

    private void tablaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseClicked
        int fila = tabla.rowAtPoint(evt.getPoint());
        int columna = tabla.columnAtPoint(evt.getPoint());
        if ((fila > -1) && (columna > -1)) {
            if (evt.isMetaDown()) {
                if (tabla.getValueAt(fila,columna)!= null) {
                    if (columna == 4) {
                        FStock s = new FStock (tabla.getValueAt(fila,0).toString());
                        if (s.hasArticulo()) {
                            Principal.panel.add (s);
                            s.show();
                            s.txtStock.requestFocus();
                            s.txtStock.selectAll();
                        }
                    }
                    else {
                        FArticulo a = new FArticulo(tabla.getValueAt(fila,0).toString());
                        if (a.hasArticulo()) {
                            Principal.panel.add (a);
                            a.show();
                        }
                    }
                    
                }
                
            } else {
                if(evt.getClickCount() == 2)
                    enviarArticulo(tabla.getValueAt(fila,0).toString(), false);
            }
        }
    }//GEN-LAST:event_tablaMouseClicked

    private int itsRow = -1;
    private int itsColumn = -1;
    private boolean fuera = false;
    
    private void tablaMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseMoved
        JTable aTable =  (JTable)evt.getSource();
        if (!fuera) {
            itsRow = aTable.rowAtPoint(evt.getPoint());
            itsColumn = aTable.columnAtPoint(evt.getPoint());
        }
        aTable.repaint();
    }//GEN-LAST:event_tablaMouseMoved

    private void tablaMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseExited
        ((JTable)evt.getSource()).repaint();
        fuera = true;
    }//GEN-LAST:event_tablaMouseExited

    private void tablaMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseEntered
        fuera = false;
    }//GEN-LAST:event_tablaMouseEntered

    private void formInternalFrameClosed(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosed
       switch(quienMeLLamo) {
            case Util.FTPV:
                break;
            case Util.FCOMPRAS:
                ((FCompras)padre).setIdArticuloFromFList("", false);
                break;
       }     

    }//GEN-LAST:event_formInternalFrameClosed

    private void tablaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tablaKeyReleased
        if (evt.getKeyCode() == 10) {
            if (tabla.getSelectedRow() > -1) {
                if(!evt.isConsumed()) 
                    evt.consume();
                enviarArticulo(tabla.getValueAt(tabla.getSelectedRow(), 0).toString(), true);
            }
        }
    }//GEN-LAST:event_tablaKeyReleased

    private void tablaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tablaKeyPressed
        if (evt.getKeyCode() == 10) {
            if(!evt.isConsumed()) 
                evt.consume();
        }
    }//GEN-LAST:event_tablaKeyPressed

    private void txtBusqMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtBusqMouseClicked
        txtBusq.selectAll();
    }//GEN-LAST:event_txtBusqMouseClicked

    private void txtBusqKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBusqKeyReleased
        if ((evt.getKeyCode() == 40) && (tabla.getRowCount() > 0)) {
            tabla.requestFocus();
        }

    }//GEN-LAST:event_txtBusqKeyReleased

    private void cbFamiliaItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbFamiliaItemStateChanged
        if(!init)
            Actualizar_Tabla();
    }//GEN-LAST:event_cbFamiliaItemStateChanged

    private void Actualizar_Tabla(){                    
        // se colocan los datos en la tabla
        String criterio = null;
        String valor = txtBusq.getText();
        DefaultTableModel datos = null;
        try {
            Long.parseLong(valor);
            if (valor.length() > 6) {
                criterio = "codigoBarras1";
                datos = Articulos.getArticulos(criterio, valor, cbFamilia.getSelectedItem().toString());
                if (datos == null)
                   criterio = "codigoBarras2";
            }
            else
                criterio = "codigo";
        } catch (Exception e) {
            criterio = "Detalle";
        }
        if (datos == null)
            datos = Articulos.getArticulos(criterio, valor, cbFamilia.getSelectedItem().toString());
        if (datos != null) {
            tabla.setModel(datos);          
            //tabla.getColumnModel().getColumn(0).setCellRenderer(new tableCellRender.Texto(itsRow, fuera));//FormatoStock ());
            //tabla.getColumnModel().getColumn(1).setCellRenderer(new tableCellRender.Texto(itsRow, fuera));//FormatoStock ());
            tabla.getColumnModel().getColumn(2).setCellRenderer(new tableCellRender.Precio(itsRow, fuera));//new FormatoPrecio());
            tabla.getColumnModel().getColumn(3).setCellRenderer(new tableCellRender.Costo(itsRow, fuera));//new FormatoCosto());
            tabla.getColumnModel().getColumn(4).setCellRenderer(new tableCellRender.Texto(itsRow, fuera));//FormatoStock ());   
        }
        else {
            int tam = tabla.getRowCount();
            for (int i = 0; i < tam; i++) 
                ((DefaultTableModel)tabla.getModel()).removeRow(0);
        }
        AnchoColumnas();
    }
    
    private void Actualizar_Tabla(String valor){
        txtBusq.setText(valor);
        // se colocan los datos en la tabla
        DefaultTableModel datos = Articulos.getArticulos("Detalle", valor, cbFamilia.getSelectedItem().toString());
        if (datos != null) {
            tabla.setModel(datos);          
            //tabla.getColumnModel().getColumn(0).setCellRenderer(new tableCellRender.Texto(itsRow, fuera));//FormatoStock ());
            //tabla.getColumnModel().getColumn(1).setCellRenderer(new tableCellRender.Texto(itsRow, fuera));//FormatoStock ());
            tabla.getColumnModel().getColumn(2).setCellRenderer(new tableCellRender.Precio(itsRow, fuera));//new FormatoPrecio());
            tabla.getColumnModel().getColumn(3).setCellRenderer(new tableCellRender.Costo(itsRow, fuera));//new FormatoCosto());
            tabla.getColumnModel().getColumn(4).setCellRenderer(new tableCellRender.Texto(itsRow, fuera));//FormatoStock ());   
        }
        else {
            int tam = tabla.getRowCount();
            for (int i = 0; i < tam; i++) 
                ((DefaultTableModel)tabla.getModel()).removeRow(0);
        }
        AnchoColumnas();
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bBuscar;
    private javax.swing.JComboBox cbFamilia;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabla;
    private javax.swing.JTextField txtBusq;
    // End of variables declaration//GEN-END:variables
}
